<template>
  <div class="search">
    <Card>
      <Row @keydown.enter.native="handleSearch">
        <Form ref="searchForm" :label-width="70" :model="searchForm" class="search-form" inline>
          <Form-item label="會員名稱" prop="username">
            <Input v-model="searchForm.username" clearable placeholder="請輸入會員名稱" style="width: 200px"
                   type="text"/>
          </Form-item>

          <Form-item label="會員暱稱" prop="nickName">
            <Input v-model="searchForm.nickName" clearable placeholder="請輸入會員暱稱" style="width: 200px"
                   type="text"/>
          </Form-item>

          <Form-item label="聯系方式" prop="mobile">
            <Input v-model="searchForm.mobile" clearable placeholder="請輸入會員聯系方式" style="width: 200px"
                   type="text"/>
          </Form-item>
          <Button class="search-btn" icon="ios-search" type="primary" @click="handleSearch">搜索</Button>
        </Form>
      </Row>
      <Row v-if="!selectedMember" class="operation padding-row">
        <Button type="primary" @click="addMember">添加會員</Button>
      </Row>

      <Table ref="table" :columns="columns" :data="data" :loading="loading" border class="mt_10"></Table>
      <Row class="mt_10" justify="end" type="flex">
        <Page :current="searchForm.pageNumber" :page-size="searchForm.pageSize" :page-size-opts="[10, 20, 50]"
              :total="total"
              show-elevator show-sizer show-total size="small" @on-change="changePage"
              @on-page-size-change="changePageSize"></Page>
      </Row>
    </Card>

    <!-- 添加用戶模态框 -->
    <Modal v-model="addFlag" title="添加會員">
      <Form ref="addMemberForm" :label-width="100" :model="addMemberForm" :rules="addRule">
        <FormItem label="手機號碼" prop="mobile" style="width: 90%;">
          <Input v-model="addMemberForm.mobile" maxlength="11" placeholder="請輸入手機號碼"/>
        </FormItem>
        <FormItem label="會員名稱" prop="username" style="width: 90%">
          <Input v-model="addMemberForm.username" maxlength="15" placeholder="請輸入會員名稱"/>
        </FormItem>

        <FormItem label="會員密碼" prop="password" style="width: 90%">
          <Input v-model="addMemberForm.password" maxlength="20" password placeholder="請輸入會員密碼" type="password"/>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="addFlag = false">取消</Button>
        <Button type="primary" @click="addMemberSubmit">确定</Button>
      </div>
    </Modal>
    <!-- 修改模态框 -->
    <Modal v-model="descFlag" :title="descTitle" width="500" @on-ok="handleSubmitModal">
      <Form ref="form" :label-width="80" :model="form" :rules="ruleValidate">

        <Input v-show="false" v-model="form.id"/>

        <FormItem label="頭像">
          <img :src="form.face || defaultPic" class="face"/>
          <Button class="upload" type="text" @click="() => {
                this.picModelFlag = true;
                this.$refs.ossManage.selectImage = true;
              }">修改
          </Button>
          <input id="file" style="display: none" type="file"/>
        </FormItem>
        <FormItem label="用戶名" prop="name">
          <Input v-model="form.username" disabled style="width: 200px"/>
        </FormItem>
        <FormItem label="用戶暱稱" prop="name">
          <Input v-model="form.nickName" style="width: 200px"/>
        </FormItem>
        <FormItem label="性别" prop="sex">
          <RadioGroup v-model="form.sex" button-style="solid" type="button">
            <Radio :label="1">
              <span>男</span>
            </Radio>
            <Radio :label="0">
              <span>女</span>
            </Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="修改密碼" prop="password">
          <Input v-model="form.newPassword" password style="width: 220px" type="password"/>
        </FormItem>
        <FormItem label="生日" prop="birthday">
          <DatePicker v-model="form.birthday" format="yyyy-MM-dd" style="width: 220px" type="date"></DatePicker>
        </FormItem>
        <FormItem label="所在地" prop="mail">
          {{ form.region || '暫無地址' }}


          <Button style="margin-left: 10px;" @click="$refs.map.open()">選擇</Button>

        </FormItem>
      </Form>
    </Modal>
    <Modal v-model="picModelFlag" width="1200px">
      <ossManage ref="ossManage" @callback="callbackSelected"/>
    </Modal>
    <multipleMap ref="map" @callback="selectedRegion"/>
  </div>
</template>

<script>
import multipleMap from "@/components/map/multiple-map";
import * as API_Member from "@/api/member.js";
import ossManage from "@/views/sys/oss-manage/ossManage";
import * as RegExp from "@/libs/RegExp.js";

export default {
  name: "member",
  components: {
    multipleMap,
    ossManage,
  },
  data() {
    return {
      defaultPic: require('@/assets/default.png'),
      descTitle: "", // modal標題
      descFlag: false, //编辑查看框
      loading: true, // 表單加载狀態
      addFlag: false, // modal显隐控制

      addMemberForm: {
        // 添加用戶表單
        mobile: "",
        username: "",
        password: "",
        storeId: ""
      },
      searchForm: {
        // 請求參數
        pageNumber: 1,
        pageSize: 10,
        order: "desc",
        username: "",
        mobile: "",
        disabled: "OPEN",
      },
      picModelFlag: false, // 選擇图片
      form: {}, // 表單數据
      addRule: {
        // 驗證规则
        mobile: [
          {required: true, message: "請輸入手機號碼"},
          {
            pattern: RegExp.mobile,
            message: "請輸入正确的手機號",
          },
        ],
        username: [{required: true, message: "請輸入會員名稱"}],
        password: [{required: true, message: "請輸入密碼"}],
      },
      ruleValidate: {}, //修改驗證
      columns: [
        {
          title: "會員名稱",
          key: "username",
          tooltip: true,
        },
        {
          title: "會員暱稱",
          key: "nickName",
          tooltip: true,
        },
        {
          title: "聯系方式",
          width: 130,
          key: "mobile",
          render: (h, params) => {
            if (params.row.mobile == null) {
              return h("div", [h("span", {}, "")]);
            } else {
              return h("div", [h("span", {}, params.row.mobile)]);
            }
          },
        },
        {
          title: "註冊時間",
          key: "createTime",
          width: 180,
        },

        {
          title: "積分數量",
          align: "left",
          width: 100,
          render: (h, params) => {
            return h(
                "div",
                {},
                params.row.point == void 0 ? "0" : params.row.point
            );
          },
        },
        {
          title: "操作",
          key: "action",
          align: "center",
          width: 200,
          fixed: "right",
          render: (h, params) => {
            return h(
                "div",
                {
                  style: {
                    display: "flex",
                    justifyContent: "center",
                  },
                },
                [
                  h(
                      "Button",
                      {
                        props: {
                          size: "small",
                          type: params.row.___selected ? "primary" : "default",
                        },
                        style: {
                          marginRight: "5px",
                          display: this.selectedMember ? "block" : "none",
                        },
                        on: {
                          click: () => {
                            this.callback(params.row, params.index);
                          },
                        },
                      },
                      params.row.___selected ? "已選擇" : "選擇"
                  ),

                  h(
                      "Button",
                      {
                        props: {
                          type: "info",
                          size: "small",
                        },
                        style: {
                          marginRight: "5px",
                          display: this.selectedMember ? "none" : "block",
                        },
                        on: {
                          click: () => {
                            this.detail(params.row);
                          },
                        },
                      },
                      "查看"
                  ),
                  h(
                      "Button",
                      {
                        props: {
                          type: "info",
                          size: "small",
                          ghost: true,
                        },
                        style: {
                          marginRight: "5px",
                          display: this.selectedMember ? "none" : "block",
                        },
                        on: {
                          click: () => {
                            this.editPerm(params.row);
                          },
                        },
                      },
                      "编辑"
                  ),
                  h(
                      "Button",
                      {
                        props: {
                          size: "small",
                          type: "error",
                        },
                        style: {
                          marginRight: "5px",
                          display: this.selectedMember ? "none" : "block",
                        },
                        on: {
                          click: () => {
                            this.disabled(params.row);
                          },
                        },
                      },
                      "禁用"
                  ),
                ]
            );
          },
        },
      ],
      data: [], // 表單數据
      total: 0, // 表單數据总數
      selectMember: [], //保存選中的用戶
    };
  },
  props: {
    // 是否为選中模式
    selectedMember: {
      type: Boolean,
      default: false,
    },
    // 已選擇用戶數据
    selectedList: {
      type: null,
      default: () => {
        return [];
      },
    },
  },
  watch: {
    selectedList: {
      handler(val) {
        this.$set(this, "selectMember", JSON.parse(JSON.stringify(val)));
        this.init(this.data);
        // 将父级數据与当前组件數据进行匹配
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    // 回调给父级
    callback(val, index) {
      this.selectMember.forEach(item => {
        item.___selected = false
      })
      this.$set(val, "___selected", !val.___selected);
      console.log(val.___selected);
      console.log(this.selectMember);
      let findUser = this.selectMember.find((item) => {
        return item.id == val.id;
      });
      // 如果沒有则添加
      if (!findUser) {
        this.selectMember.push(val);
      } else {
        // 有重复數据就删除
        this.selectMember.map((item, index) => {
          if (item.id == findUser.id) {
            this.selectMember.splice(index, 1);
          }
        });
      }

      this.$emit("callback", val);
    },
    // 初始化信息
    init(data) {
      data.forEach((item) => {
        if (this.selectMember.length != 0) {
          this.selectMember.forEach((member) => {
            if (member.id == item.id) {
              this.$set(item, "___selected", true);
            }
          });
        } else {
          this.$set(item, "___selected", false);
        }
      });
      this.data = data;
    },
    // 分頁 改变頁碼
    changePage(v) {
      this.searchForm.pageNumber = v;
      this.getData();
    },
    // 分頁 改变頁數
    changePageSize(v) {
      this.searchForm.pageSize = v;
      this.searchForm.pageNumber = 1;
      this.getData();
    },
    // 搜索
    handleSearch() {
      this.searchForm.pageNumber = 1;
      this.searchForm.pageSize = 10;
      this.getData();
    },
    //查看詳情修改
    editPerm(val) {
      this.descTitle = `查看用戶 ${val.username}`;
      this.descFlag = true;

      this.getMemberInfo(val.id);
    },
    addMember() {
      this.addFlag = true;
      this.$refs.addMemberForm.resetFields();
    },
    /**
     * 查询查看會員詳情
     */
    getMemberInfo(id) {
      API_Member.getMemberInfoData(id).then((res) => {
        if (res.result) {
          this.$set(this, "form", res.result);
        }
      });
    },

    //查询會員列表
    getData() {
      this.searchForm.storeId = window.localStorage.getItem('storeId');
      API_Member.getMemberListData(this.searchForm).then((res) => {
        if (res.result.records) {
          this.loading = false;
          this.init(res.result.records);
          this.total = res.result.total;
        }
      });
    },
    // 選中的图片
    callbackSelected(val) {
      this.picModelFlag = false;
      this.form.face = val.url;
    },
    //添加會員提交
    addMemberSubmit() {
      this.addMemberForm.storeId = window.localStorage.getItem('storeId');
      this.addMemberForm.password = this.md5(this.addMemberForm.password);
      this.$refs.addMemberForm.validate((valid) => {
        if (valid) {
          API_Member.addMember(this.addMemberForm).then((res) => {
            if (res.result) {
              this.$refs.addMemberForm.resetFields();
              this.getData();
              this.$Message.success("添加成功！");
              this.addFlag = false;
            }
          });
        }
      });
    },

    // 選中的地址
    selectedRegion(val) {
      if (val.type === 'select') {
        const paths = val.data.map(item => item.name).join(',')
        const ids = val.data.map(item => item.id).join(',')

        this.$set(this.form, 'region', paths)
        this.$set(this.form, 'regionId', ids)

      } else {
        this.$set(this.form, 'region', val.data.addr)
        this.$set(this.form, 'regionId', val.data.addrId)
      }
    },
    //查看會員
    detail(row) {
      this.$options.filters.customRouterPush({name: "member-detail", query: {id: row.id}})
    },

    //禁用會員
    disabled(v) {
      let params = {
        memberIds: [v.id],
        disabled: false,
      };
      this.$Modal.confirm({
        title: "提示",
        content: "<p>確認禁用此會員？</p>",
        onOk: () => {
          API_Member.updateMemberStatus(params).then((res) => {
            if (res.success) {
              this.$Message.success("禁用成功");
              this.getData();
            } else {
              // this.$Message.error(res.message);
            }
          });
        },
      });
    },

    // 提交修改數据
    handleSubmitModal() {
      const {nickName, sex, username, face, newPassword, id, regionId, region} = this.form;
      let time = new Date(this.form.birthday);
      let birthday = this.form.birthday === undefined ? '' :
          time.getFullYear() + "-" + (time.getMonth() + 1) + "-" + time.getDate();
      let submit = {
        regionId,
        region,
        nickName,
        username,
        sex,
        birthday,
        face,
        id
      };

      if (newPassword) {
        submit.password = this.md5(newPassword);
      }
      API_Member.updateMember(submit).then((res) => {
        if (res.result) {
          this.$Message.success("修改成功！");
          this.getData();
        }
      });
    },
  },
  mounted() {
    this.getData();
  },
};
</script>
<style lang="scss" scoped>
/deep/ .ivu-table-wrapper {
  width: 100%;
}

/deep/ .ivu-card {
  width: 100%;
}

.face {
  width: 60px;
  height: 60px;
  border-radius: 50%;
}
</style>
